<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');

class DC_Memory extends DataContainer implements editable
{

	/**
	 * Initialize the object
	 * @param string
	 */
	 
	 protected $storedData = array();
	 protected $submitButtons = array();
	 
	 protected $dcaCompound = null;
	 
	public function __construct($strTable)
	{
		parent::__construct();
		$this->intId = $this->Input->get('id');
		
		$this->Data = array();
		
		// Check whether the table is defined
		if (!strlen($strTable) || !count($GLOBALS['TL_DCA'][$strTable]))
		{
			$this->log('Could not load data container configuration for "' . $strTable . '"', 'DC_Memory __construct()', TL_ERROR);
			trigger_error('Could not load data container configuration', E_USER_ERROR);
		}

		// Build object from global configuration array
		$this->strTable = $strTable;
		
		
		$this->submitButtons['save'] = array(
			'id'=>'save',
			'formkey'=>'save',
			'class'=>'',
			'accesskey'=>'s',
			'value'=>specialchars($GLOBALS['TL_LANG']['MSC']['save'])
		);
		
		$this->submitButtons['saveNclose'] = array(
			'id'=>'save',
			'formkey'=>'saveNclose',
			'class'=>'',
			'accesskey'=>'c',
			'value'=>specialchars($GLOBALS['TL_LANG']['MSC']['saveNclose'])
		);

		
		$dcaTemplate = 'tpl_dca_view';
		
		if ($GLOBALS['TL_DCA'][$this->strTable]['config']['compoundTemplate'])
			$dcaTemplate = $GLOBALS['TL_DCA'][$this->strTable]['config']['compoundTemplate'];
		
		$this->dcaCompound = new tplCompound('tpl_cmp_'.$this->strTable.'_'.$this->intId,$dcaTemplate);
		
		// Call onload_callback (e.g. to check permissions)
		if (is_array($GLOBALS['TL_DCA'][$this->strTable]['config']['onload_callback']))
		{
			foreach ($GLOBALS['TL_DCA'][$this->strTable]['config']['onload_callback'] as $callback)
			{
				if (is_array($callback))
				{
					$this->import($callback[0]);
					$this->$callback[0]->$callback[1]($this);
				}
			}
		}
	}

	public function setData($strKey,$strValue)
	{
		$this->Data[$strKey] = $strValue;
		
		
	}
	
	
	
	public function getData($strKey)
	{
		return $this->Data[$strKey];
	}
	
	
	public function getDataArray()
	{
		$this->storedData = array();
		
		foreach ($GLOBALS['TL_DCA'][$this->strTable]['fields'] as $key=>$obj)
		{
			if ($obj['storable'])
			{
				$this->storedData[$key] = $this->getData($key);
			}
		}
	
		return $this->storedData;
	}
	
	public function setDataArray($arrData)
	{
		if (is_array($arrData))
		{
		
			foreach ($arrData as $key=>$obj)
			{
				$this->setData($key,$obj);
			}
		
			$this->storedData = $arrData;
		}
		else
		{
			$this->storedData = array();
		}
		
	}
	
	
	/**
	 * Automatically switch to edit mode
	 * @return string
	 */
	public function create()
	{
		return $this->edit();
	}


	/**
	 * Automatically switch to edit mode
	 * @return string
	 */
	public function cut()
	{
		return $this->edit();
	}


	/**
	 * Automatically switch to edit mode
	 * @return string
	 */
	public function copy()
	{
		return $this->edit();
	}


	/**
	 * Automatically switch to edit mode
	 * @return string
	 */
	public function move()
	{
		return $this->edit();
	}

	/**
	 * Autogenerate a form to edit the local configuration file
	 * @param integer
	 * @param integer
	 * @return string
	 */
	public function edit()
	{
		$return = '';
		$ajaxId = null;

		if ($this->Input->post('isAjax'))
		{
			$ajaxId = func_get_arg(1);
		}

		
		
		$dcaFormular = new tplCompound('editForm','compound_form');
		
		
		$this->objActiveRecord = $objRow;
		$this->createInitialVersion($this->strTable, $this->intId);
		
	// Build an array from boxes and rows
		$this->strPalette = $this->getPalette();
		$boxes = trimsplit(';', $this->strPalette);
		$legends = array();

		if (count($boxes))
		{
			foreach ($boxes as $k=>$v)
			{
				$eCount = 1;
				$boxes[$k] = trimsplit(',', $v);

				foreach ($boxes[$k] as $kk=>$vv)
				{
					if (preg_match('/^\[.*\]$/i', $vv))
					{
						++$eCount;
						continue;
					}

					if (preg_match('/^\{.*\}$/i', $vv))
					{
						$legends[$k] = substr($vv, 1, -1);
						unset($boxes[$k][$kk]);
					}

					elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$vv]['exclude'] || !is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$vv]))
					{
						unset($boxes[$k][$kk]);
					}
				}

				// Unset a box if it does not contain any fields
				if (count($boxes[$k]) < $eCount)
				{
					unset($boxes[$k]);
				}
			}

			$class = 'tl_tbox block';
			$fs = $this->Session->get('fieldset_states');

			// Render boxes
			foreach ($boxes as $k=>$v)
			{
				$strAjax = '';
				$blnAjax = false;
				$legend = false;
				$template = 'compound_fieldsetlegend';

				if (isset($legends[$k]))
				{
					list($key, $cls,$templateLegend) = explode(':', $legends[$k]);
					$legend = true;
					
					if ($templateLegend)
					{
						$template = $templateLegend;
					}
				}

				if (isset($fs[$this->strTable][$key]))
				{
					$class .= ($fs[$this->strTable][$key] ? '' : ' collapsed');
				}
				else
				{
					$class .= (($cls && $legend) ? ' ' . $cls : '');
				}

					
				$cmpFieldset = new tplCompound($class.'_'.$key,$template,
										array(
											'id'=>'pal_'.$key,
											'class' =>$class . ($legend ? '' : ' nolegend'),
											'legend_title' => isset($GLOBALS['TL_LANG'][$this->strTable][$key]) ? $GLOBALS['TL_LANG'][$this->strTable][$key] : $key,
											'legend_onclick' => "AjaxRequest.toggleFieldset(this, '". $key . "', '" . $this->strTable . "')"
										)
									);		
									
				// Build rows of the current box
				foreach ($v as $kk=>$vv)
				{
					if ($vv == '[EOF]')
					{
						if ($this->Input->post('isAjax') && $blnAjax)
						{
							return $strAjax . '<input type="hidden" name="FORM_FIELDS[]" value="'.specialchars($this->strPalette).'" />';
						}

						$blnAjax = false;
						$return .= "\n" . '</div>';

						continue;
					}

					if (preg_match('/^\[.*\]$/i', $vv))
					{
						$thisId = 'sub_' . substr($vv, 1, -1);
						$blnAjax = ($this->Input->post('isAjax') && $ajaxId == $thisId) ? true : false;
						$return .= "\n" . '<div id="'.$thisId.'">';

						continue;
					}

					$this->strField = $vv;
					$this->strInputName = $vv;
					$this->varValue = $this->getData($this->strField);
					
					// Call load_callback
					if (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['load_callback']))
					{
						foreach ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['load_callback'] as $callback)
						{
							if (is_array($callback))
							{
								$this->import($callback[0]);
								$this->varValue = $this->$callback[0]->$callback[1]($this->varValue, $this);
							}
						}

						$this->objActiveRecord->{$this->strField} = $this->varValue;
					}

					// Build row
					if ($blnAjax)
					{
						$strAjax .= $this->row();
					}
					else
					{	
						$fieldContainer = new tplCompound('fieldContainer','compound_div');
						$fieldContainer->addInner(new tplCompound("field_".$this->strField,"compound_static",$this->row()));
						
						if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['addSubmit'])
						{
							$fieldContainer->addInner(new tplCompound("submit_".$this->strField,"compound_submitbutton",
										array(
											'id'=>"submit_".$this->strField,
											'formkey'=>"submit_".$this->strField,
											'class'=>$GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['eval']['button_class'],
											'value'=>($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['label'][2]) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['label'][2] : $this->strField)));
											
						}				
						$cmpFieldset->addInner($fieldContainer);
					}
				}


				$dcaFormular->addInner($cmpFieldset);
		
			}
		}
	
		
		$returnLinkContainer = new tplCompound('tl_buttons','compound_div',array('id'=>'tl_buttons'));
		
		$returnLinkContainer->addInner(
						new tplCompound('header_back','compound_ahref',
							array(
								'href'=>$this->getReferer(true),
								'class'=>'header_back',
								'title'=>specialchars($GLOBALS['TL_LANG']['MSC']['backBT']),
								'accesskey'=>'b',
								'onclick'=>"Backend.getScrollOffset();",
								'value' => $GLOBALS['TL_LANG']['MSC']['backBT']
							)
						)
					);
		$this->dcaCompound->addInner($returnLinkContainer);
					
		$dcaHeadline = new tplCompound('sub_headline','compound_headline',2);
		$dcaHeadline->addInner(
							new tplCompound('sub_headline','compound_static',$GLOBALS['TL_LANG'][$this->strTable]['edit']
							));
							
		$this->dcaCompound->addInner($dcaHeadline);
		
		if ($GLOBALS['TL_DCA'][$this->strTable]['label']['name'])
		{
			$labelContainer = new tplCompound('label_name','compound_div');
		
			$labelContainer->addInner(
						new tplCompound('description','compound_static',$GLOBALS['TL_DCA'][$this->strTable]['label']['name']
							)
					);
			$this->dcaCompound->addInner($labelContainer);
		}
		
		if ($GLOBALS['TL_DCA'][$this->strTable]['label']['description'])
		{
			$labelContainer = new tplCompound('label_description','compound_div');
		
			$labelContainer->addInner(
						new tplCompound('description','compound_static',$GLOBALS['TL_DCA'][$this->strTable]['label']['description']
							)
					);
			$this->dcaCompound->addInner($labelContainer);
		}
		
		
		$this->dcaCompound->addInner(
						new tplCompound('messages','compound_static',$this->getMessages()
						)
					);
		
		$dcaFormular->addData('action', ampersand($this->Environment->request, true));
		$dcaFormular->addData('id', $this->strTable);	
		$dcaFormular->addData('class', '');
		$dcaFormular->addData('method', 'post');		
		$dcaFormular->addData('onSubmit', implode(' ', $this->onsubmit));
		$dcaFormular->addData('divClass', 'tl_formbody_edit');
		$dcaFormular->addData('FORM_SUBMIT', specialchars($this->strTable));
		$dcaFormular->addData('FORM_FIELDS', specialchars($this->strPalette));
		
		if ($this->noReload)
		{
			$dcaFormular->addData('tl_error', $GLOBALS['TL_LANG']['ERR']['general']);
		}
		
		// Add some buttons and end the form
		if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['disableSubmit'])
		{
			$returnContainer = new tplCompound('tl_formbody_submit','compound_div');
			$returnButtons = new tplCompound('tl_submit_container','compound_div');
			
			foreach ($this->submitButtons as $key=>$buttonData)
			{
				$btn = new tplCompound($key,"compound_submitbutton",$buttonData);
				$returnButtons->addInner($btn);
				
			}
	
			$returnContainer->addInner($returnButtons);
			$dcaFormular->addInner($returnContainer);
		}
	
		
		
		$this->dcaCompound->addInner($dcaFormular);
		// Reload the page to prevent _POST variables from being sent twice
		if ($this->Input->post('FORM_SUBMIT') == $this->strTable && !$this->noReload)
		{
			// Call onsubmit_callback
			if (is_array($GLOBALS['TL_DCA'][$this->strTable]['config']['onsubmit_callback']))
			{
				foreach ($GLOBALS['TL_DCA'][$this->strTable]['config']['onsubmit_callback'] as $callback)
				{
					$this->import($callback[0]);
					$this->$callback[0]->$callback[1]($this);
				}
			}

			// Reload
			if ($this->Input->post('saveNclose'))
			{
				$_SESSION['TL_INFO'] = '';
				$_SESSION['TL_ERROR'] = '';
				$_SESSION['TL_CONFIRM'] = '';

				setcookie('BE_PAGE_OFFSET', 0, 0, '/');
				$this->redirect($this->getReferer());
			}

			$this->reload();
		}

		// Set the focus if there is an error
		if ($this->noReload)
		{
			$strReload = '

<script type="text/javascript">
<!--//--><![CDATA[//><!--
window.addEvent(\'domready\', function()
{
    Backend.vScrollTo(($(\'' . $this->strTable . '\').getElement(\'label.error\').getPosition().y - 20));
});
//--><!]]>
</script>';
			
			$this->dcaCompound->addInner(new tplCompound('reload','compound_static',$strReload));
		}

		return $this->dcaCompound->parse();
	}


	/**
	 * Save the current value
	 * @param mixed
	 * @throws Exception
	 */
	protected function save($varValue)
	{
		if ($this->Input->post('FORM_SUBMIT') != $this->strTable)
		{
			return;
		}

		$arrData = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField];

		// Make sure that checkbox values are boolean
		if ($arrData['inputType'] == 'checkbox' && !$arrData['eval']['multiple'])
		{
			$varValue = $varValue ? true : false;
		}

		// Convert date formats into timestamps
		if (strlen($varValue) && in_array($arrData['eval']['rgxp'], array('date', 'time', 'datim')))
		{
			$objDate = new Date($varValue, $GLOBALS['TL_CONFIG'][$arrData['eval']['rgxp'] . 'Format']);
			$varValue = $objDate->tstamp;
		}

		// Handle entities
		if ($arrData['inputType'] == 'text' || $arrData['inputType'] == 'textarea')
		{
			$varValue = deserialize($varValue);

			if (!is_array($varValue))
			{
				$varValue = $this->restoreBasicEntities($varValue);
			}
			else
			{
				foreach ($varValue as $k=>$v)
				{
					$varValue[$k] = $this->restoreBasicEntities($v);
				}

				$varValue = serialize($varValue);
			}
		}

		// Call save_callback
		if (is_array($arrData['save_callback']))
		{
			foreach ($arrData['save_callback'] as $callback)
			{
				$this->import($callback[0]);
				$varValue = $this->$callback[0]->$callback[1]($varValue, $this);
			}
		}

		// Save the value if there was no error
		if ((strlen($varValue) || !$arrData['eval']['doNotSaveEmpty']) && $this->varValue != $varValue)
		{
			$deserialize = deserialize($varValue);
			
			$this->setData($this->strField,$deserialize);
		}
	}


	/**
	 * Return the name of the current palette
	 * @return string
	 */
	public function getPalette()
	{
		$palette = 'default';
		$strPalette = $GLOBALS['TL_DCA'][$this->strTable]['palettes'][$palette];

		// Check whether there are selector fields
		if (count($GLOBALS['TL_DCA'][$this->strTable]['palettes']['__selector__']))
		{
			$sValues = array();
			$subpalettes = array();

			foreach ($GLOBALS['TL_DCA'][$this->strTable]['palettes']['__selector__'] as $name)
			{
				$trigger = $this->getData($name);

				// Overwrite the trigger if the page is not reloaded
				if ($this->Input->post('FORM_SUBMIT') == $this->strTable)
				{
					$key = ($this->Input->get('act') == 'editAll') ? $name.'_'.$this->intId : $name;

					if (!$GLOBALS['TL_DCA'][$this->strTable]['fields'][$name]['eval']['submitOnChange'])
					{
						$trigger = $this->Input->post($key);
					}
				}

				if ($trigger != '')
				{
					if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$name]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$name]['eval']['multiple'])
					{
						$sValues[] = $name;

						// Look for a subpalette
						if (strlen($GLOBALS['TL_DCA'][$this->strTable]['subpalettes'][$name]))
						{
							$subpalettes[$name] = $GLOBALS['TL_DCA'][$this->strTable]['subpalettes'][$name];
						}
					}
					else
					{
						$sValues[] = $trigger;
						$key = $name .'_'. $trigger;

						// Look for a subpalette
						if (strlen($GLOBALS['TL_DCA'][$this->strTable]['subpalettes'][$key]))
						{
							$subpalettes[$name] = $GLOBALS['TL_DCA'][$this->strTable]['subpalettes'][$key];
						}
					}
				}
			}

			// Build possible palette names from the selector values
			if (!count($sValues))
			{
				$names = array('default');
			}
			elseif (count($sValues) > 1)
			{
				$names = $this->combiner($sValues);
			}
			else
			{
				$names = array($sValues[0]);
			}

			// Get an existing palette
			foreach ($names as $paletteName)
			{
				if (strlen($GLOBALS['TL_DCA'][$this->strTable]['palettes'][$paletteName]))
				{
					$palette = $paletteName;
					$strPalette = $GLOBALS['TL_DCA'][$this->strTable]['palettes'][$paletteName];

					break;
				}
			}

			// Include subpalettes
			foreach ($subpalettes as $k=>$v)
			{
				$strPalette = preg_replace('/\b'. preg_quote($k, '/').'\b/i', $k.',['.$k.'],'.$v.',[EOF]', $strPalette);
			}
		}

		return $strPalette;
	}
}

?>